package com.qy.controller.manage;

import com.qy.base.core.Result;
import com.qy.base.core.ResultGenerator;
import com.qy.base.utils.DateUtil;
import com.qy.model.Admin;
import com.qy.model.Roles;
import com.qy.service.AdminService;
import com.qy.service.RolesService;
import com.qy.base.core.PageBean;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zaq on 2018/06/21.
 */
@RestController
@RequestMapping("/manage/roles")
public class RolesController {
    @Resource
    private RolesService rolesService;

    @Resource
    private AdminService adminService;

    //添加角色
    @PostMapping("/add")
    public Result add(@RequestBody Roles roles) {
        roles.setActivity(true);
        roles.setCreate_time(DateUtil.getNowTimestamp());
        roles.setParent_id(1);
        rolesService.save(roles);
        return ResultGenerator.successResult();
    }

    //删除角色
    @PostMapping("/delete")
    public Result delete(@RequestBody Roles roles) {
        List<Admin> adminList = adminService.selectByCSql("role_id = " + roles.getId());
        if (adminList.isEmpty()) {
            rolesService.deleteById(roles.getId());
            return ResultGenerator.successResult();
        } else {
            return ResultGenerator.errResult();
        }
    }

    //角色列表
    @GetMapping("/list")
    public Result list(PageBean<Roles> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Roles> list = rolesService.findAll();
        for (int i = 0; i < list.size(); i++) {
            Roles roles = list.get(i);
            Condition condition = new Condition(Admin.class);
            Example.Criteria criteria = condition.createCriteria();
            criteria.andCondition("role_id =" + roles.getId());
            List<Admin> adminList = adminService.findByCondition(condition);
            if (adminList.size() == 0) {
                roles.setDeleteState(0);
            } else {
                roles.setDeleteState(1);
            }
        }
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

}
